import { useState, useEffect, useReducer } from 'react';
import api from '@API'

const dataFetchReducer = (state, action) => {
  switch (action.type) {
    case 'FETCH_INIT':
      return {
        ...state,
        isLoading: true,
        isError: false
      };
    case 'FETCH_SUCCESS':
      return {
        ...state,
        isLoading: false,
        isError: false,
        data: action.payload
      };
    case 'FETCH_FAILURE':
      return {
        ...state,
        isLoading: false,
        isError: true
      };
    default:
      throw new Error();
  }
};

const useDataApi = (initParams, initialData, serviceName) => {
  const [params, setParams] = useState(initParams);
  const [state, dispatch] = useReducer(dataFetchReducer, {
    isLoading: false,
    isError: false,
    data: initialData
  });
  useEffect(() => {
    const fetchData = async () => {
      dispatch({ type: 'FETCH_INIT' });
      try {
        const result = await api[serviceName](params)
        dispatch({ type: 'FETCH_SUCCESS', payload: result });
      } catch (error) {
        console.log(error);
        dispatch({ type: 'FETCH_FAILURE' });
      }
    };

    fetchData();
  }, [serviceName, params]);
  return [state, setParams];
};

export default useDataApi;
